<script setup lang="ts">
import { useVModel } from "@vueuse/core";
import type { TreeNodeData } from "element-plus/es/components/tree/src/tree.type";
import { useUserStoreHook } from "@/store/modules/user";
import { getFullUrl } from "@/utils/auth";
import OrgTree from "@/components/OrgTree/OrgTree.vue";
import {
  getUserListAndChildrenByOrgId,
  getUserListPages,
  getUserTreeByOrgId,
  getNewUserTreeByOrgId,
  getUserListByOrgId
} from "@/api/user/user";
import type { TreeInstance } from "element-plus";
import { ref, reactive, watch, defineExpose, defineEmits } from "vue";
import { deviceDetection } from "@pureadmin/utils";
import { ElTree } from "element-plus";
import Check from "~icons/ep/check";
import School from "~icons/ep/school";
import userAvatar from "@/assets/normal-img.png";
export type ModelValueType = string | string[] | null | undefined;

export interface UserDropdownProps {
  modelValue: Object;
  multiple?: boolean;
  width?: string;
}

const treeProps = {
  label: "name",
  children: "children",
  isLeaf: "leaf",
  class: (org: TreeNodeData) => renderClass(org)
};

export interface User {
  id: string;
  type: "user" | "dept";
  mobile?: string;
  avatar?: string;
  realName: string;
  leaf: boolean;
}
// 查询条件
const queryForm = reactive({
  realName: "",
  orgId: ""
});
const $props = withDefaults(defineProps<UserDropdownProps>(), {
  multiple: false,
  width: "30%"
});

const $emits = defineEmits<{
  (e: "update:modelValue", modelValue: ModelValueType): void;
  (e: "onSelected", userInfo: object): void;
}>();

const value = useVModel($props, "modelValue", $emits);

const userOptions = ref<User[]>([]);
const userOrgOptions = ref<User[]>([]);
const orgTreeRef = ref<TreeInstance>();
const expandedKeys = ref<string[]>([]);

const renderClass = (
  org: TreeNodeData
): string | { [key: string]: boolean } => {
  const val = userOptions.value.find(e => e.id === org.id);
  if (val) {
    return "is-active";
  } else {
    return "";
  }
};
const treeLoading = ref(false);
function onTreeSelect({ id, selected }) {
  console.log(id, selected);
  queryForm.orgId = selected ? id : "";
  onSearch();
}
const onNodeClick = (data: User) => {
  console.log("onNodeClick", data);
  if (data.type !== "user") return;
  const index = userOptions.value.findIndex(e => e.id === data.id);
  console.log("index", index);
  if ($props.multiple) {
    if (index === -1) {
      userOptions.value.push(data);
      userOptions.value.sort((a, b) => a.id.localeCompare(b.id));
    } else {
      userOptions.value.splice(index, 1);
    }
  } else {
    if (index === -1) {
      userOptions.value = [data];
    } else {
      userOptions.value.splice(index, 1);
    }
  }
  console.log("userOptions.value", userOptions.value);
};
const dialogVisible = ref(false);

watch(
  () => queryForm.realName,
  val => {
    orgTreeRef.value?.filter(val);
  }
);
const filterNode = (value: string, data: TreeNodeData): boolean => {
  if (!value) return true;
  return data.name.includes(value);
};
const open = () => {
  dialogVisible.value = true;
};
const onOpen = async () => {
  console.log("onOpen", value.value);
  const orgIdPath = useUserStoreHook().userInfo.path.split("/");
  console.log(orgIdPath);
  let path = orgIdPath[1];
  console.log(path);
  // queryForm.orgId = path;
  const orgId = useUserStoreHook().userInfo.orgId;
  queryForm.orgId = orgId;
  // getUserTreeByOrgId(path).then((res) => { // 获取树形结构
  onSearch();
  let userIds: string[] = [];
  if (Array.isArray(value.value) && value.value.length > 0) {
    userIds.push(...value.value.id);
  } else if (
    typeof value.value === "object" &&
    value.value !== null &&
    value.value !== undefined &&
    value.value.id
  ) {
    userIds.push(value.value.id);
  }
  if (userIds.length > 0) {
    const { data } = await getUserListPages(userIds);
    if (data) {
      userOptions.value = data.list.map(user => {
        return {
          id: user.id,
          realName: user.realName,
          mobile: user.mobile,
          avatar: user.avatar,
          path: user.path,
          type: "user",
          orgName: user.orgName,
          position: user.position,
          leaf: true
        } as User;
      });
      userOptions.value.sort((a, b) => a.id.localeCompare(b.id));
    }
  } else {
    userOptions.value = [];
  }
};
const handelConfirm = () => {
  console.log("handelConfirm", userOptions.value[0]);
  if ($props.multiple) {
    value.value = userOptions.value;
  } else {
    if (userOptions.value.length > 0) {
      value.value = userOptions.value[0];
    }
  }
  console.log("value.value", value.value);
  dialogVisible.value = false;
  $emits("onSelected", userOptions.value);
};
const onSearchByOrgId = (orgId: string) => {
  getUserListByOrgId(orgId).then(res => {
    console.log("res", res);
    if (res.success) {
      userOrgOptions.value = res.data.map(e => {
        return {
          id: e.id,
          realName: e.realName,
          mobile: e.mobile,
          type: "user",
          orgName: e.orgName,
          position: e.position,
          leaf: true,
          path: e.path,
          avatar: e.avatar
        } as User;
      });
    }
  });
};
const onSearch = () => {
  getUserListAndChildrenByOrgId(queryForm).then(res => {
    console.log("res", res);
    if (res.success) {
      userOrgOptions.value = res.data.map(e => {
        return {
          id: e.id,
          realName: e.realName,
          mobile: e.mobile,
          type: "user",
          orgName: e.orgName,
          position: e.position,
          leaf: true,
          path: e.path,
          avatar: e.avatar
        } as User;
      });
    }
  });
};
defineExpose({
  open
});
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    @open="onOpen"
    align-center
    draggable
    title="选择用户"
    :width="width"
  >
    <el-card shadow="never" class="org-card">
      <template #header>
        <div class="flex items-center justify-between w-full">
          <el-input
            v-model="queryForm.realName"
            placeholder="输入关键字进行查询"
            :style="{}"
            suffix-icon="search"
            clearable
          >
          </el-input>
          <el-button class="ml-[15px]" type="primary" @click="onSearch"
            >搜索</el-button
          >
        </div>
      </template>
      <div class="flex">
        <!-- 左边部门 -->
        <!-- <el-scrollbar tag="div" class="org-tree">
          <OrgTree ref="treeRef" :class="['mr-2', deviceDetection() ? 'w-full' : 'min-w-[200px]']"
            :treeLoading="treeLoading" @tree-select="onTreeSelect" />
        </el-scrollbar> -->
        <!-- 右边用户 -->
        <el-scrollbar
          tag="div"
          class="flex flex-grow org-tree flex-[3] w-full"
          style="background: #f5f7fa"
        >
          <el-tree
            ref="orgTreeRef"
            node-key="id"
            :data="userOrgOptions"
            :default-expanded-keys="expandedKeys"
            :highlight-current="true"
            :props="treeProps"
            :filter-node-method="filterNode"
            @node-click="onNodeClick"
            style="background: #f5f7fa; width: 100%"
          >
            <template #default="{ data }">
              <div class="flex items-center justify-between w-full">
                <div class="flex items-center w-full">
                  <el-avatar
                    v-if="data.type === 'user'"
                    :size="25"
                    :src="data.avatar ? getFullUrl(data.avatar) : userAvatar"
                  >
                    {{ data.realName?.charAt(0) }}
                  </el-avatar>
                  <IconifyIconOffline v-else :icon="School" :size="16" />
                  <span class="ml-[10px] w-[45px]">{{ data.realName }}</span>
                  <el-tag
                    v-if="data.type === 'user'"
                    class="ml-[10px]"
                    :hit="true"
                    round
                    size="small"
                    type="warning"
                  >
                    {{ data.orgName }}
                  </el-tag>
                  -
                  <el-tag
                    class="mr-[10px]"
                    :hit="true"
                    round
                    size="small"
                    type="primary"
                  >
                    {{ data.position }}
                  </el-tag>
                  <IconifyIconOffline
                    class="is-selected"
                    :icon="Check"
                    :size="16"
                  />
                </div>
              </div>
            </template>
          </el-tree>
        </el-scrollbar>
      </div>
    </el-card>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handelConfirm">确认</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
:deep {
  .el-tree {
    --el-tree-node-content-height: 40px;

    .el-tree-node__content {
      border-radius: 8px;
      margin: 2px 0 2px 0;
    }

    .is-active {
      color: var(--el-color-primary);

      .is-selected {
        display: block;
      }
    }
  }
}

.el-card {
  background-color: transparent;

  :deep(.el-card__header) {
    padding: 10px !important;
  }

  :deep(.el-card__body) {
    padding: 0 !important;
  }
}

.org-tree {
  height: 270px;
  padding: 5px;
}

.is-selected {
  display: none;
  padding-right: 15px;
}
</style>
